<?php
/**
 * Created by PhpStorm.
 * User: dolia
 * Date: 2016/4/6
 * Time: 14:34
 */

namespace App\Http\Controllers\Api\V1;

use App\Exceptions\Api\ApiDoneErrorException;
use App\Exceptions\Api\ApiInputErrorException;
use App\Exceptions\Api\ApiRsaEecryptErrorException;
use App\Exceptions\Api\ApiUserNotLoginErrorException;
use App\Exceptions\Api\ApiValidateErrorException;
use App\Http\Requests\Api\ApiRequest as Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\My\ResetPwdRequest;
use App\Interfaces\CollectionService;
use App\Interfaces\OrderService;
use App\Interfaces\RefundGoodsService;
use App\Interfaces\UserService;
use App\Interfaces\SmsService;
use App\Models\User;
use App\Models\MessageCode;
use App\Http\Requests\Front\UserRegisterRequest;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Session,Validator;
use Gregwar\Captcha\CaptchaBuilder;
use App\Interfaces\CartService;

class UserController extends Controller{

    /**
     * @api {post} /user/user_center 个人中心
     * @apiName User/index
     * @apiGroup User
     * @apiDescription 个人中心页面显示
     * @apiSuccess {Object[]} Object 个人中心页面信息
     * @apiSuccess {int} Object.collectionOfGoods 收藏商品数
     * @apiSuccess {int} Object.collectionOfShop 收藏店铺数
     * @apiSuccess {int} Object.numOfStatus1 待付款订单数
     * @apiSuccess {int} Object.numOfStatus2 待发货订单数
     * @apiSuccess {int} Object.numOfStatus3 待收货订单数
     * @apiSuccess {int} Object.numOfStatus4 待评价订单数
     * @apiSuccess {int} Object.numOfRefundGoods 退换货数
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     {
        "collectionOfGoods": 3,
        "collectionOfShop": 0,
        "numOfStatus1": 4,
        "numOfStatus2": 0,
        "numOfStatus3": 2,
        "numOfStatus4": 1,
        "numOfRefundGoods": 1
     }
     * @apiErrorExample Error-Response 01:
     * HTTP/1.1 202 Accepted
    {
    "message": "请登录"
    }
     */
    public function index(Request $request, CollectionService $collectionService,OrderService $orderService,RefundGoodsService $refundGoodsService){

        $user_id = $request->apiUser->get()->id;
        if(!isset($request->apiSession->session_id)){
            throw new ApiInputErrorException('非法登录，登录无效');
        }
        if (empty($user_id)) {
            throw new ApiUserNotLoginErrorException('请登录');
        }
        //dd("dgagd");
        $data = array();
        $data['collectionOfGoods']=$collectionService->getNumOfUserCollectionByType($user_id,'GOODS');
        $data['collectionOfShop']=$collectionService->getNumOfUserCollectionByType($user_id,'SHOP');
        $data['numOfStatus1']=$orderService->countOrders($user_id,1);
        $data['numOfStatus2']=$orderService->countOrders($user_id,2);
        $data['numOfStatus3']=$orderService->countOrders($user_id,3);
        $data['numOfStatus4']=$orderService->countOrders($user_id,4);
        $data['numOfRefundGoods']=$refundGoodsService->countRefundGoodsNum($user_id);

        return response()->json($data);

    }

    /**
     * @api {post} /user/login 用户登录
     * @apiName User/login
     * @apiGroup User
     * @apiDescription 用户登录
     * @apiParam {string} user_name 用户名
     * @apiParam {string} password 密码
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
    {
    "user_id": 50,
    "user_name": "343234792@qq.com",
    "phone": "18638299897",
    "email": "343234792@qq.com"
    }
     * @apiErrorExample Error-Response 01:
     * HTTP/1.1 400 Bad Request
    {
    "message": "缺少请求参数user_name"
    }
     * @apiErrorExample Error-Response 02:
     * HTTP/1.1 400 Bad Request
    {
    "message": "缺少请求参数password"
    }
     * @apiErrorExample Error-Response 03:
     * HTTP/1.1 202 Accepted
    {
    "message": "用户名不存在"
    }
     * @apiErrorExample Error-Response 04:
     * HTTP/1.1 202 Accepted
    {
    "message": "密码错误"
    }
     * @apiErrorExample Error-Response 05:
     * HTTP/1.1 202 Accepted
    {
    "message": "用户不存在"
    }
     */
    public function login(Request $request, CartService $cartService){
        if(!isset($request->apiSession->session_id)){
            throw new ApiInputErrorException('非法登录，登录无效');
        }
        //dd($request->apiSession->session_id);
        $user_name = $request->get('user_name');
        $password = $request->get('password');
        if($user_name==''){
            throw new ApiInputErrorException('缺少请求参数user_name');
        }
        if($password==''){
            throw new ApiInputErrorException('缺少请求参数password');
        }
        if(User::where('email',$user_name)->first()){
            $user = User::where('email',$user_name)->first();
        }elseif(User::where('phone',$user_name)->first()){
            $user = User::where('phone',$user_name)->first();
        }elseif(User::where('user_name',$user_name)->first()){
            $user = User::where('user_name',$user_name)->first();
        }else{
            throw new ApiDoneErrorException('用户名不存在');
        }
        //dd($request->apiUser);
        if($user){
            if ($password!=''&&md5($password)===$user->password){
                $request->apiUser->login($user);
                // dd($request->apiUser);
                $cartService->linkSessionToUser($request->apiSession->session_id,$request->apiUser->get()->id);

                $userinfo = array();//dd($userinfo);
                $userinfo['user_id'] = $user->id;
                $userinfo['user_name'] = $user->user_name;
                $userinfo['phone'] = $user->phone;
                $userinfo['email'] = $user->email;
                //dd($userinfo);
                return response()->json($userinfo);
            }else{
                throw new ApiDoneErrorException('密码错误');
            }
        }else{
            throw new ApiDoneErrorException('用户不存在');
        }
    }

    /**
     * @api {post} /user/logout 用户退出
     * @apiName User/logout
     * @apiGroup User
     * @apiDescription 用户退出
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
    {
    "user_id": 59
    }
     * @apiErrorExample Error-Response 01:
     * HTTP/1.1 202 Accepted
    {
    "message": "无效操作"
    }
     */
    public function logout(Request $request){

        $user = $request->apiUser->get();
        if($user){
            $request->apiUser->logout();
            return response()->json(['user_id'=>$user->id]);
        }else{
            throw new ApiDoneErrorException("无效操作");
        }

    }

    /**
     * @api {post} /user/reg 用户注册
     * @apiName User/reg
     * @apiGroup User
     * @apiDescription 用户注册
     * @apiParam {string} user_name 用户名
     * @apiParam {string} password 密码
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
    {
    "message": "注册成功!"
    }
     * @apiErrorExample Error-Response 01:
     * HTTP/1.1 202 Accepted
    {
    "message": "请输入您的用户名!"
    }
     * @apiErrorExample Error-Response 02:
    * HTTP/1.1 202 Accepted
    {
    "message": "用户名由字母和数字组成!"
    }
     * @apiErrorExample Error-Response 03:
     * HTTP/1.1 202 Accepted
    {
    "message": "该用户名已被使用!"
    }
     * @apiErrorExample Error-Response 04:
     * HTTP/1.1 202 Accepted
    {
    "message": "请输入您的密码!"
    }
     * @apiErrorExample Error-Response 05:
     * HTTP/1.1 202 Accepted
    {
    "message": "密码至少为6位!"
    }
     * @apiErrorExample Error-Response 06:
     * HTTP/1.1 202 Accepted
    {
    "message": "密码不超过20位!"
    }
     * @apiErrorExample Error-Response 07:
     * HTTP/1.1 202 Accepted
    {
    "message": "缺少参数phone,注册失败！"
    }
     * @apiErrorExample Error-Response 08:
     * HTTP/1.1 202 Accepted
    {
    "message": "注册失败！"
    }
     */
    public function reg(Request $request,UserService $userService,SmsService $sms){
        $session_id = $request->apiSession->session_id;
        $user_name = $request->get('user_name');
        $password = $request->get('password');

        $userRegisterRequest = new UserRegisterRequest();
        $rules = $userRegisterRequest->rules();
        $messages = $userRegisterRequest->messages();

        $reg_rules['user_name'] = $rules['user_name'];
        $reg_rules['password'] = "required|min:6|max:20";

        $reg_messages['user_name.required'] = $messages['user_name.required'];
        $reg_messages['user_name.unique'] = $messages['user_name.unique'];
        $reg_messages['user_name.regex'] = $messages['user_name.regex'];
        $reg_messages['password.required'] = $messages['password.required'];
        $reg_messages['password.min'] = $messages['password.min'];
        $reg_messages['password.max'] = $messages['password.max'];

        $validator = Validator::make($request->all(),$reg_rules,$reg_messages);
        if($validator->fails()){
            throw new ApiDoneErrorException($validator->errors()->first());
        }

        //$phone = Session::get('phone');
        $phone = Cache::get($session_id.'_phone');
        if(!$phone){
            throw new ApiDoneErrorException('缺少参数phone,注册失败！');
        }

        $reg = $userService->reg($user_name,$password,$phone);
        if($reg){
            $reg->device = 1;
            $reg->save();
            Cache::forget($session_id.'_phone');
            return response()->json(['message'=>'注册成功！']);
        }else{
            throw new ApiDoneErrorException('注册失败！');
        }


    }

    /**
     * @api {post} /user/find_password 找回密码
     * @apiName User/findPaw
     * @apiGroup User
     * @apiDescription 找回密码
     * @apiParam {string} newPaw 新密码
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
    {
    "message": "找回成功"
    }
     * @apiErrorExample Error-Response 01:
     * HTTP/1.1 400 Bad Request
    {
    "message": "缺少请求参数newPaw"
    }
     * @apiErrorExample Error-Response 02:
     * HTTP/1.1 202 Accepted
    {
    "message": "缺少参数phone,找回失败！"
    }
     * @apiErrorExample Error-Response 03:
     * HTTP/1.1 202 Accepted
    {
    "message": "找回失败！"
    }
     */
    public function findPaw(Request $request,UserService $userService){
        //$phone = $request->get('phone');
        $session_id = $request->apiSession->session_id;
// 输入手机号->发送验证码->验证验证码->找回密码
        $newPaw = $request->get('newPaw');
//        if($phone==''){
//            throw new ApiInputErrorException('缺少请求参数phone');
//        }
        if($newPaw==''){
            throw new ApiInputErrorException('缺少请求参数newPaw');
        }

        //$phone = Session::get('phone');
        $phone = Cache::get($session_id.'_phone');
        if(!$phone){
            throw new ApiDoneErrorException('缺少参数phone,找回失败！');
        }

        $findPaw = $userService->findPaw($phone,$newPaw);

        if($findPaw){
            Cache::forget($session_id.'_phone');
            return response()->json(['message'=>'找回成功']);
        }else{
            throw new ApiDoneErrorException("找回失败");
        }
    }

    /**
     * @api {post} /user/update_password 修改密码
     * @apiName User/updatePaw
     * @apiGroup User
     * @apiDescription 修改密码
     * @apiParam {string} oldPwd 原密码
     * @apiParam {string} newPwd 新密码
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
    {
    "message": "修改成功"
    }
     * @apiErrorExample Error-Response 01:
     * HTTP/1.1 400 Bad Request
    {
    "message": "缺少请求参数user_name"
    }
     * @apiErrorExample Error-Response 02:
     * HTTP/1.1 400 Bad Request
    {
    "message": "缺少请求参数oldPassword"
    }
     * @apiErrorExample Error-Response 03:
     * HTTP/1.1 400 Bad Request
    {
    "message": "缺少请求参数newPassword"
    }
     * @apiErrorExample Error-Response 04:
     * HTTP/1.1 202 Accepted
    {
    "message": "请填写原密码"
    }
     * @apiErrorExample Error-Response 05:
     * HTTP/1.1 202 Accepted
    {
    "message": "请填写新密码"
    }
     * @apiErrorExample Error-Response 06:
     * HTTP/1.1 202 Accepted
    {
    "message": "密码长度至少为6位"
    }
     * @apiErrorExample Error-Response 07:
     * HTTP/1.1 202 Accepted
    {
    "message": "密码长度不超过20位"
    }
     * @apiErrorExample Error-Response 08:
     * HTTP/1.1 202 Accepted
    {
    "message": "本次修改密码和原密码一致"
    }
     * @apiErrorExample Error-Response 09:
     * HTTP/1.1 202 Accepted
    {
    "message": "原密码错误"
    }
     * @apiErrorExample Error-Response 10:
     * HTTP/1.1 202 Accepted
    {
    "message": "修改失败"
    }
     */
    public function updatePaw(Request $request,UserService $userService){
        //$user_name = $request->get('user_name');
        $user_name = $request->apiUser->get()->user_name;
        $oldPassword = $request->get('oldPwd');
        $newPassword = $request->get('newPwd');
        //dd($user_name);
        if($user_name==''){
            throw new ApiInputErrorException('缺少请求参数user_name');
        }
        if($oldPassword==''){
            throw new ApiInputErrorException('缺少请求参数oldPassword');
        }
        if($newPassword==''){
            throw new ApiInputErrorException('缺少请求参数newPassword');
        }


        $oldPwd = User::where('user_name', $user_name)->pluck('Password');

        $resetPwdRequest = new ResetPwdRequest();
        $rules = $resetPwdRequest->rules();
        $messages = $resetPwdRequest->messages();

        $validator = Validator::make($request->all(),$rules,$messages);
        if($validator->fails()){
            throw new ApiDoneErrorException($validator->errors()->first());
        }
        if($newPassword==$oldPassword){
            throw new ApiDoneErrorException('本次修改密码和原密码一致');
        }
        if(!(md5($oldPassword)== $oldPwd)){
            throw new ApiDoneErrorException('原密码错误');
        }

        $updatePaw = $userService->updatePaw($user_name,$oldPassword,$newPassword);
        if($updatePaw){
            return response()->json(['message'=>'修改成功']);
        }else{
            throw new ApiDoneErrorException("修改失败");
        }
    }

    /**
     * @api {post} /user/validate_reg_code 验证手机验证码
     * @apiName User/validateRegCode
     * @apiGroup User
     * @apiDescription 验证手机验证码
     * @apiParam {string} phone 手机号
     * @apiParam {string} msgCode 手机验证码
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
    {
    "message": "验证成功"
    }
     * @apiErrorExample Error-Response 01:
     * HTTP/1.1 202 Accepted
    {
    "message": "缺少请求参数phone"
    }
     * @apiErrorExample Error-Response 02:
     * HTTP/1.1 202 Accepted
    {
    "message": "缺少请求参数mesCode"
    }
     * @apiErrorExample Error-Response 03:
     * HTTP/1.1 202 Accepted
    {
    "message": "两次输入的手机号不一样，请重新获取验证码"
    }
     * @apiErrorExample Error-Response 04:
     * HTTP/1.1 202 Accepted
    {
    "message": "短信验证码失效，请重新获取！"
    }
     * @apiErrorExample Error-Response 05:
     * HTTP/1.1 202 Accepted
    {
    "message": "验证码错误！"
    }
     */
    public function validateRegCode(SmsService $sms,Request $request){
        $phone = $request->phone;
        $mesCode = $request->get('msgCode');    //短信验证码

        $session_id = $request->apiSession->session_id;
        $message_id = Cache::get($session_id.'_mobile_msgCode_id');

        //$message_id = Session::get('mobile_msgCode_id');

        if($phone==''){
            throw new ApiInputErrorException('缺少请求参数phone');
        }
        if($mesCode==''){
            throw new ApiInputErrorException('缺少请求参数mesCode');
        }


        $messageCode = MessageCode::find($message_id);
        if($messageCode){
            if($phone != $messageCode->phone){
                throw new ApiDoneErrorException('两次输入的手机号不一样，请重新获取验证码');
            }
        }else{
            throw new ApiDoneErrorException('短信验证码失效，请重新获取！');
        }

        $validateRegCode = $sms->validateRegCode($message_id,$mesCode);
        if(!$validateRegCode){
            throw new ApiDoneErrorException('验证码错误！');
        }

        $messageCode = MessageCode::find($message_id);
        $messageCode->delete();
        //Session::put('phone',$phone);
        Cache::put($session_id.'_phone',$phone,date('Y-m-d H:i:s',time()));
        //Cache::save();
        //Session::save();
        return response()->json(['message'=>'验证成功']);


    }

    /**
     * @api {post} /user/sms 发送手机验证码
     * @apiName User/sms
     * @apiGroup User
     * @apiDescription 发送手机验证码
     * @apiParam {string} phone 手机号
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
    {
    "message": "发送成功！"
    }
     * @apiErrorExample Error-Response 01:
     * HTTP/1.1 202 Accepted
    {
    "message": "请输入您的手机"
    }
     * @apiErrorExample Error-Response 02:
     * HTTP/1.1 202 Accepted
    {
    "message": "请输入正确的手机格式"
    }
     * @apiErrorExample Error-Response 03:
     * HTTP/1.1 202 Accepted
    {
    "message": "该手机号已被验证"
    }
     * @apiErrorExample Error-Response 04:
     * HTTP/1.1 202 Accepted
    {
    "message": "请不要频繁发送验证码！"
    }
     * @apiErrorExample Error-Response 05:
     * HTTP/1.1 202 Accepted
    {
    "message": "发送失败！"
    }
     */
    public function sms(SmsService $sms,Request $request)
    {
        $session_id = $request->apiSession->session_id;
        if(!isset($session_id)){
            throw new ApiInputErrorException('非法登录，登录无效');
        }

        $sendLiveTime=60;
        $phone = $request->phone;


        $userRegisterRequest = new UserRegisterRequest();
        $rules = $userRegisterRequest->rules();
        $messages = $userRegisterRequest->messages();
        $sms_rules['phone'] = $rules['phone'];

        $sms_messages['phone.required'] = $messages['phone.required'];
        $sms_messages['phone.unique'] = $messages['phone.unique'];
        $sms_messages['phone.regex'] = $messages['phone.regex'];

        $validator = Validator::make($request->all(),$sms_rules,$sms_messages);
        if($validator->fails()){
            throw new ApiDoneErrorException($validator->errors()->first());
        }

        $sendTime = MessageCode::where('phone',$phone)->orderBy('send_time','desc')->pluck('send_time');

        if($sendTime){
            if(strtotime(date('Y-m-d H:i:s',time()))-strtotime($sendTime)>=$sendLiveTime){

                $message_id =  $sms->sendRegMsg($phone);
            }else{
                throw new ApiDoneErrorException('请不要频繁发送验证码！');
            }
        }else{
            $message_id =  $sms->sendRegMsg($phone);
        }

        if($message_id){
            Cache::put($session_id.'_mobile_msgCode_id',$message_id,date('Y-m-d H:i:s',time()));
            //Cache::save();
            return response()->json(['message'=>'发送成功！']);
        }else{
            throw new ApiDoneErrorException('发送失败！');
        }

    }
    public function sendEmail(Request $request)
    {
        $id = $request->apiUser->get()->id;
        //$id = $request->get('user_id');
        $email = $request->get('email');
        $is_email = User::where('email',$email)->first();
        if($is_email){
            return response()->json(['status'=>0,'message'=>'该邮箱已验证！']);
        }
        $user = User::findOrFail($id);

        //生成随机字符串
        $str='1234567890';
        $randStr = str_shuffle($str);//打乱字符串
        $code= substr($randStr,0,4);//substr(string,start,length);

        $data = ['email'=>$email,'name'=>$user->user_name,'user_id'=>$user->id,'code'=>$code];
        $result = Mail::send('front.user.activemail',$data, function ($message) use ($data) {
            $message->to($data['email'])->subject('欢迎注册我们的网站，请激活您的账号！');
        });
        if($result){
            $user->code = $code;
            $user->check_type=1;
            $user->send_time=date('Y-m-d H:i:s',time());
            $user->save();
            return response()->json(['status'=>$result]);
        }else{
            return response()->json(['status'=>$result,'message'=>'发送失败！']);
        }
    }


} 